package com.whs.demo.actors;

import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.utils.ScissorStack;

/**
 * 裁剪类
 * 
 * @Description:
 * @author whs
 * @date 2015-11-24 下午4:29:51
 * @version V1.0
 */
public class ScissorsGroup
    extends Group {

    // 截取区域，避免改变Yzhou
    private Rectangle cullingArea = new Rectangle();
    private Rectangle scissor;

    @Override
    public void draw(Batch batch, float parentAlpha) {
        /*
         * 先 获得组的坐标系矩阵，进行矩阵转换，然后设置batch的坐标系矩阵为转换后的矩阵
         */
        applyTransform(batch, computeTransform());
        cullingArea.set(0.0F, 0, getWidth(), getHeight());

        if (ScissorStack.pushScissors(calculateScissors(batch.getTransformMatrix()))) {
            setTransform(true);
            drawChildren(batch, parentAlpha);
            batch.flush();
            ScissorStack.popScissors();
        }

        // 矩阵还原
        resetTransform(batch);
        super.draw(batch, parentAlpha);
    }

    /**
     * 计算裁剪区域
     * 
     * @author whs
     * @date 2015-11-24 下午4:34:10
     * @param matrix4
     * @return
     * @Description:
     */
    private Rectangle calculateScissors(Matrix4 matrix4) {
        Rectangle rectangle = Rectangle.tmp;
        rectangle.set(0.0F, 0.0F, getWidth(), getHeight());
        if (scissor == null) {
            scissor = new Rectangle();
        }
        ScissorStack.calculateScissors(getStage().getCamera(), matrix4, rectangle, scissor);
        return scissor;
    }

}
